/**
 * 
 * @returns 订单主页
 */
import "../../css/goods.css"
import "../../css/order.css"

import { Col, Modal, Row, Button, Input, Checkbox, Table, Tag, Pagination, Tooltip, Skeleton, Card, message, DatePicker } from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import { useEffect, useRef, useState, PureComponent } from "react";
import { GetGoods } from "../../api/goods";
import { getWidth } from "../../utils/getWidth";
import { GetOrderStatistics, GetOrders } from "../../api/order";
import { GetOrderDetails } from "../../api/home";


import ExportJsonExcel from 'js-export-excel';
// import { formatTime } from '@/utils/utils';
import dayjs from "dayjs";
import CountUp from "react-countup";







// 搜索框属性 start
const { Search } = Input;
const suffix = (
    <AudioOutlined
        style={{
            fontSize: 16,
            color: '#1677ff',
        }}
    />
);


//搜索框属性 end




const options = [
    {
        label: '已完成',
        value: "a",
        checked: true

    },
    {
        label: '已取消',
        value: "b",
    },
    {
        label: '直营',
        value: 'c',
    }
];
//复选框 end


// 销售数据详情
const columns_orderSon = [
    {
        title: '序号',
        dataIndex: 'Index',
        key: 'Index',
        with: 20

    },
    {
        title: '图片',
        dataIndex: 'photo',
        key: 'photo',
        render: (text) => <img style={{ width: 60, borderRadius: 5 }} src={text}></img>

    },
    {
        title: '商品名称',
        dataIndex: 'goodsName',
        key: 'goodsName'
    },
    {
        title: '类型',
        dataIndex: 'goodsType',
        key: 'goodsType',
        render: (text) => {
            return <div>{text==="" || text===null? "其他":text}</div>
        }
    },

    {
        title: '供应商',
        dataIndex: 'merchant',
        key: 'merchant',
        ellipsis: {
            showTitle: false,
        },
        width: 120,
        render: (text) => (
            <Tooltip placement="topLeft" title={text}>
                <Tag color='blue' bordered={false} className='primary-tag'>{text}</Tag>
            </Tooltip>
        )
        
    },
    {
        title: '单价',
        dataIndex: 'price',
        key: 'price',
        ellipsis: {
            showTitle: false,
        },
        width: 120,
        render: (text) => <Tooltip placement="topLeft" title={text}>
            <Tag color='blue' bordered={false} className='primary-tag'>￥ {text}</Tag>
        </Tooltip>
    },
    {
        title: '数量',
        dataIndex: 'number',
        key: 'number',
        render: (text) => <Tag color='blue' bordered={false} className='primary-tag'>{text}</Tag>
    },

    {
        title: '小计',
        dataIndex: 'money',
        key: 'money',
        ellipsis: {
            showTitle: false,
        },
        width: 120,
        render: (text) => <Tooltip placement="topLeft" title={text}>
            <Tag color='red' bordered={false} className='danger-tag'>￥ {text}</Tag>
        </Tooltip>
    },

   

];


//订单管理主页
const OrderIndex = () => {
    document.info = [
        {
            title: "订单管理-主页",
            url: "/order",
        }]


    //表格数据
    const [tableData, setTable] = useState([]);
    //条件查询条件
    const [likeSelect, setLike] = useState({
        key: "",
        isComplete: -1,
        isCancel: -1,
        isSend: -1,
        isDirectly: -1,
        begin: "",
        end: ""
    });
    //分页
    const [pages, setPage] = useState({
        page: 1,
        limit: 10,
        total: 0
    })


    //加载效果
    const [load, setLoad] = useState({
        loading: false,
        isFirst: true,
        sonFirst: true
    });

    // const [itable, setITable] = useState([]);
    var itable = [];




    //数据导出方法
    const downloadFileToExcel = () => {

      
        const getRepaymentPlanList = itable;  //从props中获取数据源
        let option = {};  //option代表的就是excel文件
        let dataTable = [];  //excel文件中的数据内容
        if (getRepaymentPlanList && getRepaymentPlanList.length > 0) {
            for (let i in getRepaymentPlanList) {  //循环获取excel中每一行的数据
                let _planDay = dayjs(getRepaymentPlanList[i].planDay, true);  //格式化日期（自定义方法）
                let obj = {
                    '订单号': getRepaymentPlanList[i].id,
                    '商户': getRepaymentPlanList[i].merchant,
                    '供应商':getRepaymentPlanList[i].supplier,
                    '种类': getRepaymentPlanList[i].goodsCategory,
                    '总金额': getRepaymentPlanList[i].money,
                    '时间':getRepaymentPlanList[i].time,
                }
                dataTable.push(obj);  //设置excel中每列所获取的数据源
            }
        }
        option.fileName = '订单数据';  //excel文件名称
        option.datas = [
            {
                sheetData: dataTable,  //excel文件中的数据源
                sheetName: '表格数据',  //excel文件中sheet页名称
                sheetFilter: ['订单号', '商户', '供应商', '种类', '总金额','状态','时间'],  //excel文件中需显示的列数据
                sheetHeader: ['订单号', '商品', '供应商', '种类', '总金额','状态','时间'],  //excel文件中每列的表头名称
            }
        ]
        let toExcel = new ExportJsonExcel(option);  //生成excel文件
        toExcel.saveExcel();  //下载excel文件
    }












    //销售数据模态框
    const [open_a, setOpen_a] = useState(false);
    const [orderSonTable, setOrderSonTable] = useState([]); //获取销售数据详情

    //获取销售数据的单个详情
    const getOrderDetails = async (props) => {
        const res = await GetOrderDetails({ id: props });
        if (res.result !== 0) {
            message.error("数据有误");
        }
        res.data.map((d, i) => { return d.Index = i + 1 });
        setOrderSonTable(res.data);
        setLoad((load) => ({ ...load, sonFirst: false }));
    }


    //详情按钮
    const ordersDetail = (props) => {
        setLoad((load) => ({ ...load, sonFirst: true }));
        setOpen_a(true);
        getOrderDetails(props);

    }


    const [open, setOpen] = useState(false);
    const showModal = () => {
        setOpen(true);
    };
    const hideModal = () => {
        setLike((likeSelect) => ({
            ...likeSelect,
            isComplete: -1,
            isCancel: -1,
            isDirectly: -1,
            begin: '',
            end: ''
        }));
        console.log(checkRef, "ojk");
        setOpen(false);
    };






    //卡片大小弹性设置
    const [cardWidth, setCard] = useState(6);

    //日期选择
    const { RangePicker } = DatePicker;

    //卡片大小弹性设置
    const [cardData, setCardData] = useState([]);


    //下架/上架按钮
    const MyButton = (hang) => {
        if (hang.hang.inventory === 0 && hang.hang.sales === 0 && hang.hang.isShelve === 0 || hang.hang.isBan === 1) {
            return
        } else {
            if (hang.hang.isShelve === 0) {
                return <div className="success btn">上架</div>
            } else {
                return <div className="warning btn">下架</div>
            }
        }
    }


    const dateChange = (value, myDate) => {
        setLike((likeSelect) => ({ ...likeSelect, begin: myDate[0], end: myDate[1] }))
    }

    //复选框 start
    const onChange = (checkedValues) => {
        if (checkedValues.includes("a")) {
            setLike((likeSelect) => ({ ...likeSelect, isComplete: 1 }));
        } else {
            setLike((likeSelect) => ({ ...likeSelect, isComplete: -1 }));
        }

        if (checkedValues.includes("b")) {
            setLike((likeSelect) => ({ ...likeSelect, isCancel: 1 }));
        } else {
            setLike((likeSelect) => ({ ...likeSelect, isCancel: -1 }));
        }

        if (checkedValues.includes("c")) {
            setLike((likeSelect) => ({ ...likeSelect, isDirectly: 1 }));
        } else {
            setLike((likeSelect) => ({ ...likeSelect, isDirectly: -1 }));
        }

        if (checkedValues.length === 0) {

            setLike((likeSelect) => ({
                ...likeSelect,
                isComplete: -1,
                isCancel: -1,
                isDirectly: -1
            }));
        }


    };

    //点击搜索按钮触发事件
    const onSearch = (value, _e, info) => {
        setLike((likeSelect) => ({ ...likeSelect, key: value }));
    }

    //表格表头
    const columns = [
        {
            title: '订单号',
            dataIndex: 'id',
            key: 'id',
            width: 150
        },
        // {
        //     title: '商品',
        //     dataIndex: 'goodsNames',
        //     key: 'goodsNames',
        //     width: 100,
        //     ellipsis: {
        //         showTitle: false,
        //     },
        //     render: (text) => (
        //         <Tooltip placement="topLeft" title={text?.join(",")}>
        //             {text?.join(",")}
        //         </Tooltip>
        //     ),
        // },
        {
            title: '商户',
            dataIndex: 'merchant',
            key: 'merchant',
            width: 150,
            ellipsis: {
                showTitle: false,
            },
            render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>,

        },

        {
            title: '供应商',
            dataIndex: 'supplier',
            key: 'supplier',
            width: 140,
            ellipsis: {
                showTitle: false,
            },
            render: (text) => (
                <div>
                    {
                        text === null ?
                            <Tag color="red" style={{ color: "#f56c6c" }} bordered={false}>直营</Tag> :
                            <div><Tooltip placement="topLeft" title={text}><Tag color="blue" style={{ color: "#409eff" }} bordered={false}>{text}</Tag></Tooltip></div>}
                </div>
            ),
        },


        {
            title: '种类',
            dataIndex: 'goodsCategory',
            key: 'goodsCategory',
            width: 60,
            render: (text) => <div><Tag color="blue" style={{ color: "#409eff" }} bordered={false}>{text}</Tag></div>
        },
        // {
        //     title: '总数量',
        //     dataIndex: 'goodsCount',
        //     key: 'goodsCount',
        //     width: 80,
        //     render: (text) => <div><Tag color="blue" style={{ color: "#409eff" }} bordered={false}>{text}</Tag></div>
        // },
        {
            title: '总金额',
            dataIndex: 'money',
            key: 'money',
            width: 100,
            ellipsis: {
                showTitle: false,
            },
            render: (text) => <Tooltip placement="topLeft" title={text}><Tag color="red" style={{ color: "#f56c6c" }} bordered={false}>￥ {text}</Tag></Tooltip>
        },
      
        {
            title: '状态',
            dataIndex: 'isComplete',
            key: 'isComplete',
            width: 80,
            render: (text, hang) => (
                <div>
                    {text === 0 && hang.isCancel === 0 && <Tag color="warning" className="warning-tag" bordered={false}>未完成</Tag>}
                    {text === 1 && <Tag color="success" className="success-tag" bordered={false}>已完成</Tag>}
                    {text === 0 && hang.isCancel === 1 && <Tag color="info" className="info-tag" bordered={false}>已取消</Tag>}
                </div>
            ),
        },
        // {
        //     title: '发货数',
        //     dataIndex: 'sendCount',
        //     key: 'sendCount',
        //     width: 80,
        //     render: (text) => <div><Tag color="blue" style={{ color: "#409eff" }} bordered={false}>{text}</Tag></div>
        // },
        // {
        //     title: '收货数',
        //     dataIndex: 'receiveCount',
        //     key: 'receiveCount',
        //     width: 80,
        //     render: (text) => <div><Tag color="blue" style={{ color: "#409eff" }} bordered={false}>{text}</Tag></div>
        // },
        {
            title: '时间',
            dataIndex: 'time',
            key: 'time',
            ellipsis: {
                showTitle: false
            },
            render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
        },
        {
            title: '操作',
            dataIndex: '',
            key: '',
            width: 150,
            fixed: 'right',
            render: (text, hang) => (
                <div style={{ width: 150 }}>
                    <div style={{ marginLeft: "5px" }} className="primary btn" size="small"
                        onClick={() => { ordersDetail(hang.id) }}
                    >详情</div>
                    {hang.isDirectly == 1 && <div className="success-cell btn">发货</div>}

                </div>
            ),
        },

    ];

    //实时获取页面宽度
    const [windowWidth, setWindowWidth] = useState(getWidth());

    // 标记一下   card响应改变
    useEffect(() => {
        const widthSize = () => {
            setWindowWidth(getWidth());
        };
        window.addEventListener("resize", widthSize);
        if (windowWidth.width <= 1280) {
            setCard(12);
        }

        if (windowWidth.width <= 1000) {
            setCard(24);
        }

        if (windowWidth.width > 1000) {
            setCard(12);
        }
        if (windowWidth.width > 1280) {
            setCard(6);
        }

        return () => {
            window.removeEventListener("resize", widthSize);
        };
    });

    //搜索框
    const myRef = useRef("");
    const checkRef = useRef('');

    const onSearchData = () => {
        // setLike((likeSelect) => ({ ...likeSelect, key: myRef.current.input.value }));

        if (myRef.current.input.value == "" || myRef.current.input.value == null) {
            setLike((likeSelect) => ({ ...likeSelect, key: "" }));
        }
    }


    useEffect(() => {
        //获取表格数据
        const getData = async () => {
            setLoad((load) => ({ ...load, loading: true }));

            const cardRes = await GetOrderStatistics();
            const OrderRes = await GetOrders({
                page: pages.page,
                limit: pages.limit,
                key: likeSelect.key,
                isComplete: likeSelect.isComplete,
                isCancel: likeSelect.isCancel,
                isSend: likeSelect.isSend,
                isDirectly: likeSelect.isDirectly
            });

            OrderRes.data.data.map((d, i) => d.Index = i + 1);
            if (cardRes.result !== 0 || OrderRes.result !== 0) {
                message.error("数据有误")
            }
            //订单表格数据
            setTable(OrderRes.data);
            //分页数据
            setPage((pages) => ({ ...pages, total: OrderRes.data.total }));
            //订单统计数据
            setCardData(cardRes.data);
            //加载效果
            setLoad((load) => ({ ...load, loading: false }));
            setLoad((load) => ({ ...load, isFirst: false }));

        }
        getData();

    }, [pages.page, likeSelect.isComplete, likeSelect.isDirectly, likeSelect.isCancel, likeSelect.key]);


    //分页改变事件
    const pageChange = (props) => {

        setPage((pages) => ({ ...pages, page: props }));
    }
    const gridStyle = {
        textAlign: 'center',
        fontSize: "18px",
        paddingLeft: "20px",
        paddingRight: "20px",
        boxSizing: "border-box"
    };

    //确认导出时间
    const importData = async () => {
        const OrderRes = await GetOrders({
            page: 1,
            limit: 9999,
            begin: likeSelect.begin,
            end: likeSelect.end,
            isComplete: likeSelect.isComplete,
            isCancel: likeSelect.isCancel,
            isSend: likeSelect.isSend,
            isDirectly: likeSelect.isDirectly
        });
        OrderRes.data.data.map((d, i) => d.Index = i + 1);
        if (OrderRes.result !== 0) {
            message.error("数据有误");
            hideModal();
        } else {
            hideModal();

        }
        console.log(OrderRes.data.data, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        let aa = JSON.parse(JSON.stringify(OrderRes.data.data))
        //    console.log("..........",aa);
        //   setITable(aa);
        // console.log(itable,";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;");
        itable = aa;
        downloadFileToExcel();
    }
    return (
        <>

            <div className="Containers orderIndex"> <Skeleton active loading={load.isFirst} paragraph={{ rows: 15 }}>

                <div style={{ padding: "5px" }}>
                    <Row gutter={[10, 2]}>
                        <Col className="gutter-row" span={cardWidth}>
                            <div>

                                <Card title={<div>订单总数，
                                    <CountUp start={0} end={cardData.validOrderCount} duration="1.5" />
                                    {/* {cardData.validOrderCount} */}
                                    </div>} className="order-card-a" style={gridStyle} bordered={false}>
                                    有效订单，
                                    <CountUp start={0} end={cardData.validOrderCount} duration="1.5" />
                                    {/* {cardData.validOrderCount} */}
                                </Card>
                            </div>
                        </Col>
                        <Col className="gutter-row" span={cardWidth} >
                            <div>
                                <Card title={<div>有效金额，
                                    <CountUp start={0} end={cardData.orderMoney} duration="1.5" />
                                    {/* {cardData.orderMoney} */}
                                    </div>} className="order-card-b" style={gridStyle} bordered={false} >
                                    商品数量，  <CountUp start={0} end={cardData.goodsCount} duration="1.5" />
                                    {/* {cardData.goodsCount} */}
                                </Card>
                            </div>
                        </Col>
                        <Col className="gutter-row" span={cardWidth}>
                            <div>
                                <Card title={<div>下单人次，
                                    <CountUp start={0} end={cardData.orderPeople} duration="1.5" />
                                    {/* {cardData.orderPeople} */}
                                    </div>} className="order-card-c" style={gridStyle} bordered={false}>
                                    商品种类， <CountUp start={0} end={cardData.goodsCategory} duration="1.5" />
                                    {/* {cardData.goodsCategory} */}
                                </Card>
                            </div>
                        </Col>
                        <Col className="gutter-row" span={cardWidth}>
                            <div>
                                <Card title={<div>完成订单数，
                                    <CountUp start={0} end={cardData.orderPeople} duration="1.5" />
                                    {/* {cardData.orderPeople} */}
                                    </div>} className="order-card-d" style={gridStyle} bordered={false}>
                                    发货订单数，
                                    <CountUp start={0} end={cardData.goodsCategory} duration="1.5" />
                                    {/* {cardData.goodsCategory} */}
                                </Card>
                            </div>
                        </Col>

                    </Row>
                </div>



                <div className="goodsIndexContainer">
                    <div className="good-head">
                        <div><Button type="primary" onClick={showModal}>数据导出</Button></div>
                        <Modal title="数据导出"
                            open={open}
                            onOk={hideModal}
                            onCancel={hideModal}
                            footer={null}
                        >
                            <Checkbox.Group options={options} defaultValue={[]} onChange={onChange} style={{ marginTop: 20 }} />
                            <RangePicker onChange={dateChange} style={{ marginTop: 25, width: "100%" }} />

                            <Button type="primary" block style={{ marginTop: 20 }} onClick={() => { importData() }}>确认导出</Button>

                        </Modal>

                        <div>
                            <Search
                                placeholder="输入订单号搜索"
                                onSearch={onSearch}
                                allowClear
                                style={{
                                    width: 500,
                                }}
                                onChange={(e) => onSearchData(e)}
                                ref={myRef}
                            />
                        </div>


                        <div>
                            <Checkbox.Group options={options} defaultValue={[]} onChange={onChange} ref={checkRef} />


                        </div>
                    </div>



                    <div className="good-data">

                        <Table dataSource={tableData.data} columns={columns} bordered pagination={false} loading={load.loading}
                            style={{ marginTop: "10px" }}
                        />

                        <div className="page-layout">
                            <Pagination defaultCurrent={1} total={pages.total} onChange={(value) => { pageChange(value) }} />
                        </div>



                        <Modal
                            title="详情"
                            okButtonProps={false}
                            open={open_a}
                            onOk={() => setOpen_a(false)}
                            onCancel={() => setOpen_a(false)}
                            width={1200}
                            footer={null}
                        >
                            <Skeleton active loading={load.sonFirst} paragraph={{ rows: 5 }}>
                                <Table dataSource={orderSonTable} columns={columns_orderSon} bordered pagination={false} loading={load.sonLoading}
                                    style={{ marginTop: "5px" }}
                                    scroll={{
                                        y: 500
                                    }}
                                />
                            </Skeleton>



                        </Modal>
                    </div>
                </div>
            </Skeleton>
            </div>
        </>
    )
}

export default OrderIndex